<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/6 0006
 * Time: 下午 3:52
 */
namespace Admin\Model;
use Think\Model,Think\Upload,Think\Image,Think\Page;

class GoodsModel extends Model
{
    protected $insertFiles =array(
        'goods_name','market_price','shop_price','is_on_sale','attr_id','attr_value',
        'goods_desc','brand_id', 'cat_id','type_id','promote_price,','level_id',
        'promote_start_date,promote_end_date','is_new','is_best','is_hot','sort_num'
        ,'is_floor'
        );
    protected $updateFiles =array
    ('id','goods_name','market_price','shop_price','attr_id','attr_value',
    'is_on_sale','goods_desc','brand_id', 'cat_id','type_id','promote_price,','level_id',
     'promote_start_date,promote_end_date','is_new','is_best','is_hot','sort_num'
    ,'is_floor'
    );
    protected $tableName ='goods';
    protected $_validate = array(
        array('cat_id','require','必须选择主分类',1),
        array('goods_name','require','商品名称不能为空',1,'',3),
        array('market_price','currency','市场价格必须是货币类型','',3),
        array('shop_price','currency','本店价格必须是货币类型','',3),
        array('promote_price','currency','会员价格必须是货币类型','',3),
    );

  /*  protected $_auto = array(
        array('addtime','getTime',1,'callback'),
    );
    protected function getTime(){
        return date('Y-m-d H:i:s',time());
    }*/
   public function _before_insert(&$data,$option){
       if($_FILES['logo']['error'] == 0){
           $ret = Upload('logo','Goods',array(
           array(650,650),
           array(350, 350),
           array(150, 150),
           array(50, 50),
          ));
           $data['logo']     =$ret['images'][0];
           $data['mbig_logo'] = $ret['images'][1];
           $data['big_logo'] = $ret['images'][2];
           $data['mid_logo'] = $ret['images'][3];
           $data['sm_logo'] = $ret['images'][4];
       }
        $data['addtime'] = date('Y-m-d H:i:s',NOW_TIME);
       if(!$data['addtime'])
           unset($data['addtime']);
       if(!$data['promote_start_date'])
           unset($data['promote_start_date']);
       if(!$data['promote_end_date'])
           unset($data['promote_end_date']);
       $data['goods_desc']  = removeXSS($_POST['goods_desc']);
   }
    public function _before_update(&$data,$option){
        $id = $data['id'];

        if(!$data['promote_start_date'])
            unset($data['promote_start_date']);
        if(!$data['promote_end_date'])
            unset($data['promote_end_date']);

        //修改商品属性
        $gaid =I('post.goods_attr_id');
        $attrValue = I('post.attr_value');
        $gaModel = D('goods_attr');
        $_i = 0;
        foreach($attrValue as $k => $v){
            foreach ($v as $k1 =>$v1) {
                if ($gaid[$_i] == ""&&!empty($v1)){
                    $gaModel->add(array(
                        'goods_id' => $id,
                        'attr_id' => $k,
                        'attr_value' => $v1
                    ));
                }else {
                    $gaModel->where(array(
                        'id' => array('eq', $gaid[$_i])
                    ))->setField('attr_value', $v1);
                }
                $_i++;
            }
        }
       //修改扩展分类
        $ecid = I('post.ext_cat_id');
        $gcModel = D('goods_cat');
        $gcModel->where(
            array(
                'goods_id' =>array('eq',$data['id'])
            ))->delete();
        if($ecid){
            foreach($ecid as $k => $v){
                if(empty($v))
                    continue;
                $gcModel->add(
                    array(
                        'cat_id' => $v,
                        'goods_id'=>$data['id']
                    )
                );
            }
        }
        //修改会员价格
        $mp = I('post.price');
        $mpModel = D('member_price');
        $mpModel->where(
            array(
            'goods_id'=> array('eq',$id)
        ))->delete();
        foreach ($mp as $k => $v){
            $_v =(float)$v;
            if($_v > 0){
                $mpModel->add(array(
                    'price' =>$_v,
                    'level_id'=>$k,
                    'goods_id'=>$id
                ));
            }
        }
        //修改商品图片时删掉硬盘上的图片
        if($_FILES['logo']['error'] == 0){
            $ret = Upload('logo','Goods',array(
            array(650,650),
            array(350, 350),
            array(150, 150),
            array(50, 50),
            ));
            if($ret['ok'] == 1)
            {
                $data['mbig_logo'] = $ret['images'][1];
                $data['big_logo'] = $ret['images'][2];
                $data['mid_logo'] = $ret['images'][3];
                $data['sm_logo'] = $ret['images'][4];
            }
            else
            {
                $this->error = $ret['error'];
                return FALSE;
            }
            $oldLogo = $this->field('logo,mbig_logo,big_logo,mid_logo,sm_logo')->find($id);
            deleteImage($oldLogo);
        }
        //处理相册图片
        if(isset($_FILES['pic'])) {
            $pics = array();
            foreach ($_FILES['pic']['name'] as $k => $v) {
                $pics[] = array(
                    'name' => $v,
                    'type' => $_FILES['pic']['type'][$k],
                    'tmp_name' => $_FILES['pic']['tmp_name'][$k],
                    'error' => $_FILES['pic']['error'][$k],
                    'size' => $_FILES['pic']['size'][$k],
                );
            }
            $_FILES = $pics;
            $gpModel = D('goods_pic');

            foreach ($pics as $k => $v) {
                if ($v['error'] == 0) {
                    $ret = Upload($k, 'Goods', array(
                        array(650, 650),
                        array(350,350),
                        array(50, 50),
                    ));
                    if ($ret['ok'] == 1) {
                        $gpModel->add(
                            array(
                                'pic' => $ret['images'][0],
                                'big_pic' => $ret['images'][1],
                                'mid_pic' => $ret['images'][2],
                                'sm_pic' => $ret['images'][3],
                                'goods_id' => $id
                            ));
                    }
                }
            }
        }
        $data['goods_desc']  = removeXSS($_POST['goods_desc']);
    }
    public function _before_delete($option){
        $id = $option['where']['id'];
        //删除商品库存量
        $gnModel = D('goods_number');
        $gnModel->where(array(
            'goods_id'=>array('eq',$id)
        ))->delete();
        //删除商品属性
        $gaModel = D('goods_attr');
        $gaModel->where(
            array('goods_id' => array(
                'eq',$id
            ))
        )->delete();
        //删除商品分类
        $gcModel = D('goods_cat');
        $gcModel->where(
            array('goods_id'=>array('eq',$id))
        )->delete();
        //删除相册中的图片
        $gpModel = D('goods_pic');
        $pics = $gpModel->field('pic,sm_pic,mid_pic,big_pic')->where(
            array('goods_id' =>array('eq',$id))
        )->select();
        foreach ($pics as $k =>$v)
            deleteImage($v);
        $gpModel->where(array('goods_id' =>array('eq',$id)))->delete();

        //删除原来的图片
        $oldLogo = $this->field('logo,mbig_logo,big_logo,mid_logo,sm_logo')->find($id);
        deleteImage($oldLogo);

        //删除会员价格
        $mpModel = D('member_price');
        $mpModel->where(
            array(
                'goods_id' => array('eq',$id)
            )
        )->delete();
    }
    public function _after_insert(&$data,$option){
        //处理商品属性
        $attrVlaue = I('post.attr_value');
        $gaModel = D('goods_attr');
        foreach ($attrVlaue as $k => $v){
           $v = array_unique($v);
            foreach ($v as $k1 =>$v1){
                $gaModel->add(array(
                    'goods_id' => $data['id'],
                    'attr_id' => $k,
                    'attr_value' =>$v1
                ));
            }
        }
        //处理扩展类
        $ecid = I('post.ext_cat_id');
        if($ecid){
            $gcModel = D('goods_cat');
            foreach($ecid as $k => $v){
                if(empty($v))
                continue;
                $gcModel->add(
                   array(
                       'cat_id' => $v,
                       'goods_id'=>$data['id']
                   )
                );
            }
        }
        //处理图片
        if(isset($_FILES['pic'])){
            $pics = array();
            foreach ($_FILES['pic']['name'] as $k =>$v){
                $pics[] =array(
                    'name' => $v,
                    'type' =>$_FILES['pic']['type'][$k],
                    'tmp_name'=>$_FILES['pic']['tmp_name'][$k],
                    'error'=>$_FILES['pic']['error'][$k],
                    'size'=>$_FILES['pic']['size'][$k],
                );
            }
            $_FILES = $pics;
            $gpModel = D('goods_pic');

            foreach ($pics as $k => $v){
                if($v['error'] ==0){
                    $ret = Upload($k,'Goods',array(
                        array(650, 650),
                        array(350,350),
                        array(50, 50),
                    ));
                    if($ret['ok'] ==1)
                    {
                        $gpModel->add(
                            array(
                                'pic' => $ret['images'][0],
                                'big_pic' => $ret['images'][1],
                                'mid_pic' => $ret['images'][2],
                                'sm_pic'  => $ret['images'][3],
                                'goods_id'=> $data['id']
                            ));
                    }
                }
            }
        }

        //处理会员价格
        $mb =I('post.price');
        $mpModel = D('member_price');
        foreach($mb as $k => $v){
            $_v = (float)$v;
            if($_v > 0){
            $mpModel->add(
                array(
                'price' => $_v,
                'level_id' => $k,
                'goods_id' => $data['id']
                )
            );
            }
        }
    }
    public function search($perPage=5)
    {
        $where = array();

        $gn =I('get.gn');
        if($gn){
            $where['goods_name'] = array('like',"%{$gn}%"); //where goods_name like %$gn%;
        }
        //价格
        $fp = I('get.fp');
        $tp = I('get.tp');
        if($fp && $tp){
            $where['shop_price'] = array('between' ,array($fp,$tp));//where shop_price between $fp and $tp
        }else if($fp){
            $where['shop_price'] = array('egt',$fp); //where shop_price >= $fp;
        }else if($tp){
            $where['shop_price'] = array('elt',$tp); //where shop_price >= $tp;
        }
        //是否上架
        $ios = I('get.ios');
        if($ios){
            $where['a.is_on_sale'] = array('eq',$ios); //where is_on_sale = $ios;
        }


        //排序
        $orderby = 'a.id';
        $orderway = 'desc';
        $odby = I('get.odby');
        if($odby){
            if($odby == "id_asc"){
                $orderway = 'asc';
            }else if($odby =="price_desc"){
                $orderby = "shop_price";
            }else if($odby =="pirce_asc"){
                $orderby  = 'shop_price';
                $orderway = 'asc';
            }
        }
        //添加时间排序
        $fa = I('get.fa');
        $ta = I('get.ta');
        if($fa && $ta){
            $where['addtime'] =array('between',array($fa,$ta));
        }else if($fa){
            $where['addtime'] =array('egt',$fa);
        }else if($ta){
            $where['addtime'] =array('elt',$ta);
        }
        //品牌的搜索
        $brandId = I('get.brand_id');
        if($brandId)
            $where['brand_id'] =array('eq',$brandId);

        //分类的搜索
        $catId =I('get.cat_id');
        if($catId){
            $gids = $this ->getGoodsIdByCatId($catId);
            if(empty($gids)){
                $where['a.id'] = array('eq','');
            }else{
                $where['a.id'] = array('in',$gids);
            }
        }
        //分页
        $count = $this->where($where)->alias(a)->count();
        $page_obj = new Page($count,$perPage);
        $PageString = $page_obj->show();

        $data = $this->order("$orderby $orderway")
                     ->field('a.*,b.brand_name,c.cate_name,GROUP_CONCAT(e.cate_name) ext_cat_name')
                     ->alias('a')
                     ->join(
                         'LEFT JOIN __BRAND__ b ON a.brand_id = b.id
                        LEFT JOIN __CATEGORY__ c ON a.cat_id = c.id
                        LEFT JOIN __GOODS_CAT__ d ON a.id = d.goods_id
                        LEFT JOIN __CATEGORY__ e ON d.cat_id = e.id
                        '
                     )
                     ->where($where)
                     ->limit($page_obj->firstRow.','.$page_obj->listRows)
                     ->group('a.id')
                     ->select();
        return array(
            'data' =>$data,
            'page' =>$PageString
         );
    }
    public function getGoodsIdByCatId($catId){
        //先取出所有子分类
        $catModel = D('Admin/Category');
        $children = $catModel->getChildren($catId);
        $children[] = $catId;
        $gids = $this->field('id')->where(
            array('cat_id' =>array('in',$children))
        )->select();
        $gcModel = D('goods_cat');
        $gids1 = $gcModel->field('DISTINCT goods_id id')->where(
            array('cat_id'=> array(
                'in',$children
            ))
        )->select();
        if($gids && $gids1){
            $gids =array_merge($gids,$gids1);
        }elseif($gids1)
            $gids = $gids1;
        $id = array();
        foreach ($gids as $k => $v){
            if(!in_array($v['id'],$id))
                $id[] = $v['id'];
        }
        return $id;
    }
    //取出正在促销的商品
    public function getPromoteGoods($limit=5){
        $today = date('Y-m-d H:i:s');
        return $this->field('id,goods_name,mid_logo,promote_price')
            ->where(array(
                'is_on_sale' =>array('eq','Y'),
                'promote_price' =>array('gt',0),
                'promote_start_date' =>array('elt',$today),
                'promote_end_date' =>array('egt',$today)
            ))->limit($limit)->order('sort_num ASC')->select();
    }
    //取出三种推荐商品
    public function getRecGoods($recType,$limit =5){
        return $this->field('id,goods_name,mid_logo,shop_price,goods_desc,is_best,is_hot,is_new')
            ->where(array(
                'is_on_sale'=>array('eq','Y'),
                $recType =>array('eq','是')
            ))->limit($limit)->order('sort_num ASC')->select();
    }
    //获取会员价格
    public function getMemberPrice($goodsId){
        $today=date('Y-m-d H:i:s');
        $levelId=session('level_id');
        $promotePrice = $this->field('promote_price')->where(
            array(
                'id'=>array('eq',$goodsId),
                'promote'=>array('gt',0),
                'promote_start_date'=>array('elt',$today),
                'promote_end_date' =>array('egt',$today)
            )
        )->find();
        //判断会员有没有登录
        if($levelId){
            $mpModel = D('member_price');
            $mpData  = $mpModel->field('price')->where(array(
                'goods_id'=>array('eq',$goodsId),
                'level_id'=>array('eq',$levelId)
            ))->find();
        //这个级别有没有设置会员价格
        if($mpData['price']){
            if($promotePrice['promote_price']){
                return min($promotePrice['promote_price'],$mpData['price']);
            }else{
                return $mpData['price'];
            }
        }else{
            //如果没有这个级别的价格就直接返回本店价格
            $p = $this->field('shop_price')->find($goodsId);
            if($promotePrice['promote_price']){
                return min($promotePrice['promote_price'],$p['shop_price']);
            }else{
                return $p['shop_price'];
            }
        }
    }else{
            $p = $this->field('shop_price')->find($goodsId);
            if($promotePrice['promote_price']){
                return min($promotePrice['promote_price'],$p['shop_price']);
            }else{
                return $p['shop_price'];
            }
        }
    }

    public function cat_search($catId,$pageSize=5){
        /**************  搜索 *************/
        $goodsId = $this->getGoodsIdByCatId($catId);
        !$goodsId && $goodsId =array(0);
        $where['a.id']=array('in',$goodsId);
        $brandId =I('get.brand_id');
        if($brandId)
            $where['a.brand_id']=array('eq',(int)$brandId);
        $price = I('get.price');
        if($price){
            $price = explode('-',$price);
            $where['a.shop_price'] =array('between',$price);
        }
        $gaModel = D('goods_attr');
        $attrGoodsId = NULL;
        foreach($_GET as $k => $v){
            if(strpos($k,'attr_')===0){
                $attrId = str_replace('attr_','',$k);
                $attrName = strrchr($v,'-');
                $attrValue = str_replace($attrName,'',$v);
                $gids = $gaModel->field('GROUP_CONCAT(goods_id)gids')
                    ->where(array(
                        'attr_id'=>array('eq',$attrId),
                        'attr_value'=>array('eq',$attrValue)
                ))->find();
                if($gids['gids']){
                    $gidsp['gids'] =explode(',',$gids['gids']);
                    if($attrGoodsId ===NULL)
                        $attrGoodsId=$gids['gids'];
                    else{
                        $attrGoodsId =array_intersect($attrGoodsId,$gids['gids']);
                        if(empty($attrGoodsId)){
                            $where['a.id']=array('eq',0);
                            break;
                        }

                    }
                }else{
                    $attrGoodsId = array();
                    $where['a.id']=array('eq',0);
                    break;
                }
            }
        }
        if($attrGoodsId)
            $where['a.id'] =array('in',$attrGoodsId);
        /************** 翻页 ***************/
        $count = $this
            ->alias('a')
            ->field('COUNT(a.id) goods_count,GROUP_CONCAT(a.id) goods_id')
            ->where($where)->find();
        $data['goods_id']=explode(',',$count['goods_id']);

        $page = new Page($count['goods_count'],$pageSize);
        $data['page'] = $page->show();
        $oderby = 'x1';
        $oderway = 'desc';
        $odby =I('get.odby');
        if($odby){
            if($odby =='addtime')
                $oderby ='a.addtime';
            if(strpos($odby,'price_')===0){
                $oderby='a.shop_price';
                if($odby =='price_asc')
                    $oderway ='asc';
            }
        }
        $data['data'] = $this->alias('a')
            ->field('a.id,a.goods_name,a.mid_logo,a.shop_price,SUM(b.goods_number) x1')
            ->join('LEFT JOIN __ORDER_GOODS__ b ON (a.id=b.goods_id AND b.order_id IN(SELECT id FROM __ORDER__ WHERE pay_status="是"))')
            ->where($where)
            ->group('a.id')
            ->limit($page->firstRow.','.$page->listRows)
            ->order("$oderby $oderway")
            ->select();
        return $data;
    }
    public function key_search($key,$pageSize=5){
        /**************  搜索 *************/
        //$goodsId = $this->getGoodsIdByCatId($catId);
        //!$goodsId && $goodsId =array(0);
        $goodsId = $this->alias('a')->field('GROUP_CONCAT(DISTINCT a.id) gids')
            ->join('LEFT JOIN __GOODS_ATTR__ b ON a.id=b.goods_id')
            ->where(array(
                'a.is_on_sale'=>array('eq','Y'),
                'a.goods_name'=>array('exp',"LIKE '%$key%' OR a.goods_desc LIKE '%$key%' OR attr_value LIKE '%$key%'"),
            ))->find();
        $goodsId =explode(',',$goodsId['gids']);
        $where['a.id']=array('in',$goodsId);
        $brandId =I('get.brand_id');
        if($brandId)
            $where['a.brand_id']=array('eq',(int)$brandId);
        $price = I('get.price');
        if($price){
            $price = explode('-',$price);
            $where['a.shop_price'] =array('between',$price);
        }
        $gaModel = D('goods_attr');
        $attrGoodsId = NULL;
        foreach($_GET as $k => $v){
            if(strpos($k,'attr_')===0){
                $attrId = str_replace('attr_','',$k);
                $attrName = strrchr($v,'-');
                $attrValue = str_replace($attrName,'',$v);
                $gids = $gaModel->field('GROUP_CONCAT(goods_id)gids')
                    ->where(array(
                        'attr_id'=>array('eq',$attrId),
                        'attr_value'=>array('eq',$attrValue)
                    ))->find();
                if($gids['gids']){
                    $gidsp['gids'] =explode(',',$gids['gids']);
                    if($attrGoodsId ===NULL)
                        $attrGoodsId=$gids['gids'];
                    else{
                        $attrGoodsId =array_intersect($attrGoodsId,$gids['gids']);
                        if(empty($attrGoodsId)){
                            $where['a.id']=array('eq',0);
                            break;
                        }

                    }
                }else{
                    $attrGoodsId = array();
                    $where['a.id']=array('eq',0);
                    break;
                }
            }
        }
        if($attrGoodsId)
            $where['a.id'] =array('in',$attrGoodsId);
        /************** 翻页 ***************/
        $count = $this
            ->alias('a')
            ->field('COUNT(a.id) goods_count,GROUP_CONCAT(a.id) goods_id')
            ->where($where)->find();
        $data['goods_id']=explode(',',$count['goods_id']);

        $page = new Page($count['goods_count'],$pageSize);
        $data['page'] = $page->show();
        $oderby = 'x1';
        $oderway = 'desc';
        $odby =I('get.odby');
        if($odby){
            if($odby =='addtime')
                $oderby ='a.addtime';
            if(strpos($odby,'price_')===0){
                $oderby='a.shop_price';
                if($odby =='price_asc')
                    $oderway ='asc';
            }
        }
        $data['data'] = $this->alias('a')
            ->field('a.id,a.goods_name,a.mid_logo,a.shop_price,SUM(b.goods_number) x1')
            ->join('LEFT JOIN __ORDER_GOODS__ b ON (a.id=b.goods_id AND b.order_id IN(SELECT id FROM __ORDER__ WHERE pay_status="是"))')
            ->where($where)
            ->group('a.id')
            ->limit($page->firstRow.','.$page->listRows)
            ->order("$oderby $oderway")
            ->select();
        return $data;
    }
}
